<template>
  <div :class="{ loginWrap: true }">
    <div class="text_prompt">
      <span>登录</span>
      <br />
      <span>Login to continue</span>
    </div>

    <div class="ranyu_from">
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" status-icon>
        <div class="inputWrap">
          <div class="inputWrap_text">
            <p>手机号</p>
          </div>

          <div class="phone_input">
            <div class="phone_input_wrap">
              <el-select v-model="ruleForm.areaCode" class="custom-select" @change="educationLevel">
                <el-option v-for="item in phoneList" :key="item.number" :value="item.number">
                  <template #default>{{ item.number }} {{ item.name }}</template>
                </el-option>
              </el-select>
            </div>

            <div class="phone_input_myphone">
              <el-form-item prop="phoneNumber">
                <el-input
                  v-model="ruleForm.phoneNumber"
                  type="text"
                  placeholder="请输入手机号"
                  :prefix-icon="Iphone"
                  class="myphone_input"
                />
              </el-form-item>
            </div>
          </div>
        </div>

        <div class="inputWrap">
          <div class="inputWrap_text">
            <p>验证码</p>
          </div>

          <div class="inputWrap_input">
            <el-form-item prop="captcha">
              <el-input
                v-model="ruleForm.captcha"
                type="text"
                :show-controls="false"
                placeholder="请输入验证码"
              />
            </el-form-item>
          </div>
          <div class="getVerify">
            <a href="javascript:void(0)" :class="{ disabled: isDisabled }" @click="getVerify">
              获取验证码 {{ countdown }}
            </a>

            <a href="javascript:void(0)" @click="toRegister">新用户注册</a>
          </div>
        </div>
        <div class="btnWrap">
          <el-button
            type="primary"
            style="margin-bottom: 10px"
            color="#6861ff"
            :disabled="!ischeck"
            @click="submitForm(ruleFormRef)"
          >
            登录
          </el-button>
          <!-- <el-button type="primary" style="margin-bottom: 10px" color="#6861ff" @click="mockReq()">
            Mock
          </el-button> -->
          <div class="agreenWrap">
            <div>
              <el-checkbox v-model="ischeck" size="large" />
            </div>
            <div>
              <p>
                我接受并同意该网站的
                <a href="javascript:void(0)" @click="clickAgreen">《RANYU用户注册与服务协议》</a>
                <a href="javascript:void(0)" @click="clickAgreen">《RANYU用户信息保护政策》</a>
                等相关规定。
              </p>
            </div>
          </div>
        </div>
      </el-form>
    </div>
  </div>
  <showAgreen ref="showagreen" @agreen="agreeAgreement"></showAgreen>
</template>

<script lang="ts" setup>
import NProgress from "@/utils/nprogress";
import AuthAPI from "@/api/auth/index";
import MOCK from "@/api/system/new";
import { setAccessToken, setUserType, setUserBizId } from "@/utils/auth";
//未注册提示弹框
import router from "@/router";
import showStatusStore from "@/store/modules/protocolDisplayStatus"; //展示状态
import { ref, onMounted, defineEmits, watch } from "vue";
const ischeck = ref<boolean>(false); //是否同意协议
import showAgreen from "@/views/login/components/showAgreen.vue"; //协议展示组件
import type { FormInstance, FormRules } from "element-plus";
const showagreen = ref<any>();
import { Iphone } from "@element-plus/icons-vue";
const phoneList = ref<
  {
    name: string;
    number: string;
  }[]
>([
  {
    name: "中国",
    number: "+86",
  },
  {
    name: "香港",
    number: "+852",
  },
  {
    name: "澳门",
    number: "+853",
  },
  {
    name: "台湾",
    number: "+886",
  },
]);
//正则规则
const RulePattern = ref({
  phone: "^[1][3-9][0-9]{9}$",
  captcha: "^[0-9]{4}$",
});

interface RuleForm {
  phoneNumber: string;
  captcha: string;
  areaCode: string;
}
// 注册信息
const ruleForm = ref<RuleForm>({
  phoneNumber: showStatusStore().myFrom.phone,
  captcha: "",
  areaCode: "+86",
});
watch(
  //登陆注册页面输入框联动
  () => ruleForm.value.phoneNumber,
  (newValue) => {
    showStatusStore().myFrom.phone = newValue;
  }
);
const rules = computed<FormRules<RuleForm>>(() => ({
  phoneNumber: [
    { required: false, message: "必须输入电话号码", trigger: "blur " },
    { pattern: RulePattern.value.phone, message: "必须输入正确的电话格式", trigger: "blur" },
  ],
  captcha: [
    {
      required: false,
      message: "必须输入验证码",
      trigger: "blur ",
    },
    {
      pattern: RulePattern.value.captcha,
      message: "请输入正确的验证码",
      trigger: "blur",
    },
  ],
}));
// 正则选择
const educationLevel = (key: string) => {
  switch (key) {
    case "+86": //中国大陆
      RulePattern.value.phone = "^[1][3-9][0-9]{9}$";
      break;
    case "+886": //台湾
      RulePattern.value.phone = "^[09|6][0-9]{9}$";
      break;
    case "+852": //香港
      RulePattern.value.phone = "^[9|6][0-9]{7}$";
      break;
    case "+853": //澳门
      RulePattern.value.phone = "^[6][0-9]{7}$";
      break;
    default:
      break;
  }
};
const ruleFormRef = ref<FormInstance>();

const isDisabled = ref<boolean>(false); // 是否禁用
const countdown = ref<any>(); // 倒计时
// 点击同意协议才能使用接口
const agreeAgreement = () => {
  ischeck.value = true;
};

const clickAgreen = async () => {
  showagreen.value.openAr();
};

// // 获取验证码
const getVerify = async () => {
  if (isDisabled.value) {
    return;
  }
  const regx = new RegExp(RulePattern.value.phone);
  if (!regx.test(ruleForm.value.phoneNumber)) {
    ElMessage({
      message: "请输入正确的手机号",
      type: "error",
    });
    return;
  }
  try {
    // 校验用户是否注册
    NProgress.start();
    let validation = await AuthAPI.hasSigned({
      userAccount: ruleForm.value.phoneNumber,
    });

    if (validation == null || validation.isAgreement == "0" || validation.isStandard == "0") {
      // 用户未注册提示去注册
      showStatusStore().changeDialogVisible(true);
      NProgress.done();
    } else if (validation.isAgreement == "1" || validation.isStandard == "1") {
      // 继续获取验证码
      try {
        await AuthAPI.getVerificationCode({
          phone: ruleForm.value.phoneNumber,
          type: "reg",
          areaCode: ruleForm.value.areaCode,
        });
        NProgress.done();
        // 禁用按钮并设置倒计时
        isDisabled.value = true;
        countdown.value = 60;

        // 启动倒计时
        const timer = setInterval(() => {
          countdown.value--;

          // 倒计时结束
          if (countdown.value <= 0) {
            countdown.value = "";
            clearInterval(timer); // 清除定时器
            isDisabled.value = false; // 启用按钮
          }
        }, 1000);
      } catch {
        // 验证码获取失败
        ElMessage({
          message: "获取验证码失败",
          type: "error",
        });
        NProgress.done();
      }
    }
  } catch {
    //账号校验失败
    ElMessage.error("验证码获取失败");
    NProgress.done();
  }
};

watch(
  () => ruleForm.value.phoneNumber,
  () => {
    showStatusStore().myFrom.phone = ruleForm.value.phoneNumber;
  }
);

// 关闭协议框
const emits = defineEmits(["change"]);
// 去注册
const toRegister = () => {
  emits("change", true);
};
const mockReq = async () => {
  await MOCK.mockTest();
};
//点击登录
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid) => {
    if (valid) {
      NProgress.start();
      try {
        let userInfo = await AuthAPI.userLogin(ruleForm.value);
        if (userInfo.httpMsg == "验证码错误或已过期" || userInfo.httpMsg == "操作失败") {
          ElMessage({
            message: userInfo.httpMsg + "",
            type: "warning",
          });

          NProgress.done();
          return;
        }
        localStorage.setItem("phone", userInfo.imUserId);
        setAccessToken(userInfo.token); //存储token
        setUserType(userInfo.userType); //存储用户类型
        setUserBizId(userInfo.userBizId); //存储用户id
        Number(userInfo.userType) === 3 ? router.push("/dashboard") : router.push("/register");
        NProgress.done();
      } catch (error) {
        error == "Error: 未签署协议/规范"
          ? showStatusStore().changeDialogVisible(true)
          : ElMessage({
              message: error + "",
              type: "error",
            });
        NProgress.done();
      }
    }
  });
};

onMounted(() => {
  showStatusStore().changemyPage("登录");
});
</script>
<style lang="scss" scoped>
:deep(.el-input__wrapper) {
  padding: 1px 11px;
}
:deep(.el-icon svg) {
  width: 20px;
  height: 20px;
}
:deep(.el-select__wrapper) {
  height: 68px;
  width: 68px;
  outline: none !important;
  min-height: auto !important;
  padding: 4px 12px !important;
  span {
    font-size: 16px;
  }
  .el-select__selection {
    position: unset !important;
  }
}
.el-checkbox.el-checkbox--large {
  width: 14px !important;
  height: 14px !important;
  // .el-checkbox__inner {
  //   // width: 14px !important;
  //   // height: 14px !important;
  // }
}
.custom-checkbox {
  --size: 24px;
  --icon-size: 24px;
}
.disabled {
  pointer-events: none; /* 禁用点击事件 */
  opacity: 0.5; /* 降低透明度 */
}
:deep(.el-form-item__content) {
  height: 68px;
}

.phone_input {
  display: flex;
  .phone_input_wrap {
    flex: 1;
    line-height: 0 !important;
    margin-right: 16px;
  }

  .phone_input_myphone {
    flex: 5;
    .el-input {
      height: 68px;
    }
  }
}

:deep(.el-input__prefix .el-icon) {
  font-size: 22px;
  /* 修改图标大小 */
  color: #7d7c8f;
  /* 修改图标颜色 */
}
:deep(.el-form) {
  display: flex;
  flex-direction: column;
}
::v-deep .el-input__inner {
  color: "#555556";
  /* 修改文字颜色 */
  font-size: 16px;
  /* 修改文字大小 */
  font-family: "思源黑体";
  /* 修改字体 */
}

::v-deep .el-input__inner::placeholder {
  color: #555556;
  font-size: 18px;
  font-weight: normal;
  line-height: 20px;
  text-align: left;
  letter-spacing: 0px;
}
.inputWrap {
  display: flex;
  flex-direction: column;
  > div {
    flex: 1;
  }
}
a {
  text-decoration: none;
  color: #6861ff;
}

.getVerify {
  margin-top: 10px;
  display: flex;
  justify-content: space-between;
  font-size: 16px;
  font-weight: bold;
  letter-spacing: 0px;
}

.ranyu_from {
  margin-top: 80px;
}

.loginWrap {
  display: flex;
  flex-direction: column;
  .text_prompt {
    text-align: center;
    font-family: "思源黑体";
    line-height: 20px;
    text-align: center;
    letter-spacing: 0px;
    span {
      display: block;
    }

    span:nth-of-type(1) {
      color: #3d3d3d;
      font-size: 30px;
      font-weight: 500;
    }

    span:nth-of-type(2) {
      margin-top: 20px;
      font-size: 20px;
      font-weight: normal;
    }
  }
}

.inputWrap_input {
  .el-input {
    height: 68px;
  }
}

.btnWrap {
  margin-top: 54px;

  button {
    width: 100%;
    height: 55px;
    font-size: 24px;
  }

  .agreenWrap {
    display: flex;
    font-size: 16px;
    font-weight: normal;
    line-height: 29px;
    letter-spacing: 0px;
    p {
      margin: 0;
      margin-left: 12px;
    }
    > div {
      padding-right: 10px;
    }
  }
}

.inputWrap_text {
  p {
    font-family: Source Han Sans;
    font-size: 26px;
    font-weight: normal;
    line-height: 20px;
    text-align: left;
    letter-spacing: 0px;
  }
}
@media (max-width: 766px) {
  .inputWrap_text {
    display: none;
  }
}
</style>
